<script lang="ts" setup>
/**
 * axios axios 配置
 * myMixin 页面公共方法
 */
let axios: any = inject('$axios');
import { useRouter } from 'vue-router';
const router = useRouter();

/**
 * seMIDIMessageEvent
 * searchOptions 搜索配置
 * handelSearch 搜索暴露方法
 */
const searchOptions = reactive([
  {
    label: '信息编号',
    value: '',
    key: 'no',
    placeholder: '请输入信息编号',
    options: [],
    type: 'input',
    size: 3,
  },
  {
    label: '手机号',
    value: '',
    key: 'mobile',
    placeholder: '请输入手机号',
    options: [],
    type: 'input',
    size: 3,
  },
  {
    label: '微信号',
    value: '',
    key: 'number',
    placeholder: '请输入微信号',
    options: [],
    type: 'input',
    size: 3,
  },
  {
    label: '是否付费',
    value: '',
    key: 'is_pay',
    placeholder: '请选择是否付费',
    size: 3,
    options: [
      {
        value: '',
        label: '全部',
      },
      {
        value: '1',
        label: '是',
      },
      {
        value: '2',
        label: '否',
      },
    ],
    type: 'select',
  },
  {
    label: '按时间段',
    value: '',
    key: 'betweenTime',
    placeholder: '请选择开始/结束时间',
    options: [],
    type: 'datetimerange',
    size: 5,
  },
  {
    label: '发布地区',
    value: '',
    key: 'area',
    placeholder: '请选择信息发布地区',
    options: [],
    type: 'city',
    size: 3,
  },
]);
const searchItem = ref();
const searchForm = ref();
const handelSearch = (params) => {
  searchForm.value = Object.assign(
    {
      no: '', // 信息编号
      mobile: '', // 手机号
      number: '', // 微信号
      is_pay: '', // 是否付费
      betweenTime: '', // 时间段
      area: '', // 发布地区
    },
    params,
  );
  // 省市区数据
  if (params.area.length) {
    searchForm.value.area_province_id = params.area[0];
    searchForm.value.area_city_id = params.area[1];
    searchForm.value.area_district_id = params.area[2];
    delete searchForm.value.area;
  }
  searchForm.value.created_at_start = params.betweenTime[0] || '';
  searchForm.value.created_at_end = params.betweenTime[1] || '';
  delete searchForm.value.betweenTime;
  getTableList();
};

/**
 * 列表表格：
 * tableOptions 表格组件配置
 * columns 表格columns配置
 * tableData 表格数据参数
 * loadingTable 加载表格数据loading
 * getTableList 获取表格数据方法
 * handlePaginationChange 切换currentPage或切换pageSize
 */
const tableOptions = reactive({
  showPagination: true,
  defaultSort: { prop: 'plain_end_time', order: 'descending' },
  paginationConfig: {
    total: 10,
    currentPage: 1,
    pageSize: 10,
  },
});
const columns = ref([
  { type: 'selection', label: '', align: 'center', width: '60' },
  { prop: 'no', label: '信息编号', align: 'center', width: '160' },
  { prop: 'cat_1_msg', label: '类别', align: 'center' },
  {
    label: '发布地区',
    align: 'center',
    width: '180',
    render: ({ row }) => {
      return h('span', `${row.area_whole_msg}`);
    },
  },
  {
    label: '订单类型',
    align: 'center',
    render: ({ row }) => {
      return h('span', row.style == 1 ? '普通' : 'VIP');
    },
  },
  {
    label: '是否付费',
    align: 'center',
    render: ({ row }) => {
      return h('span', row.is_pay == 1 ? '是' : '否');
    },
  },
  { prop: 'refresh_times', label: '刷新次数', align: 'center', width: '100' },
  {
    label: '用户',
    width: '150',
    align: 'center',
    render: ({ row }) => {
      if (!row.nickname && !row.number) {
        return h(ElLink, { type: 'primary' }, '催促');
      }
      return h(
        'div',
        {
          style: {
            height: '100%',
            width: '90%',
            margin: '0 auto',
            'text-align': 'left',
          },
        },
        [
          h(
            'p',
            {
              style: {
                'line-height': '15px',
                'margin-bottom': '3px',
              },
            },
            '微信昵称：' + row.nickname || '',
          ),
          h(
            'p',
            { style: { 'line-height': '15px' } },
            '微信号：' + row.number || '',
          ),
        ],
      );
    },
  },
  {
    prop: 'plain_end_time',
    label: '计划结束时间',
    align: 'center',
    sortable: 'true',
    type: 'date',
    width: '180',
  },
  { prop: 'created_at', label: '创建时间', align: 'center', width: '180' },
  {
    label: '信息状态',
    align: 'center',
    width: '140',
    render: ({ row }) => {
      if (row.status == undefined) return;
      let obj = {
        0: {
          title: '支付中',
          type: 'primary',
        },
        1: {
          title: '待移交',
          type: 'primary',
        },
        2: {
          title: '已取消',
          type: 'danger',
        },
        3: {
          title: '已删除',
          type: 'danger',
        },
        4: {
          title: '已驳回',
          type: 'danger',
        },
        5: {
          title: '已通过',
          type: 'success',
        },
        6: {
          title: '已移交',
          type: 'success',
        },
        7: {
          title: 'vip待创建',
          type: 'warning',
        },
        8: {
          title: '超时',
          type: 'warning',
        },
      };
      return h(
        ElTag,
        { effect: 'dark', type: obj[row.status].type },
        obj[row.status].title,
      );
    },
  },
  {
    prop: 'visit_day',
    label: '超时天数（天）',
    align: 'center',
  },
  {
    prop: 'visit_appraise',
    label: '用户评价',
    align: 'center',
    width: '100',
  },
  {
    label: '回访评价',
    align: 'center',
    width: '150',
    render: ({ row }) => {
      return h(ElRate, {
        disabled: true,
        disabledVoidColor: '#cdd0d6',
        modelValue: row.visit_score,
      });
    },
  },
  {
    prop: 'op_time',
    label: '操作时间',
    align: 'center',
    width: '180',
  },
  {
    label: '操作',
    align: 'center',
    width: '120',
    render: ({ row }) => {
      let arr = [
        {
          name: '查看',
          type: 'primary',
          icon: '',
          disabled: false,
          command: handelWatch,
        },
        {
          name: '删除',
          type: 'primary',
          icon: '',
          disabled: false,
          command: handelDelete,
        },
      ];
      if (row.status == 2 || row.status == 3) {
        arr[1].disabled = true;
      }
      let showButton = arr.map((item) => {
        return h(
          ElButton,
          {
            type: item.type,
            icon: item.icon,
            text: true,
            disabled: item.disabled,
            style: {
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'start',
              height: '25px',
              width: '50%',
              margin: '0  5px',
              padding: 0,
            },
            onClick: () => item.command(row),
          },
          item.name,
        );
      });
      return h(
        'div',
        {
          style: {
            textAlign: 'center',
            width: '70%',
            height: '100%',
            margin: '0 auto',
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
          },
        },
        showButton,
      );
    },
  },
]);
const tableData = ref([]);
const loadingTable = ref(false);
const getTableList = async (page?: any) => {
  loadingTable.value = true;
  let params = Object.assign(
    {
      page: page ? page : tableOptions.paginationConfig.currentPage,
      limit: tableOptions.paginationConfig.pageSize,
      is_order_plain_end_time: tableSort.value,
    },
    searchForm.value,
  );
  let res = await axios.getMessageDataList(params);
  loadingTable.value = false;
  if (res.data.code != 200)
    return ElMessage({
      message: res.data.message,
      type: 'error',
    });
  tableData.value = res.data.data.list;
  tableOptions.paginationConfig = {
    total: Number(res.data.data.pageData.count),
    currentPage: Number(res.data.data.pageData.page),
    pageSize: 10,
  };
};
const handlePaginationChange = (currentPage, pageSize) => {
  tableOptions.paginationConfig.currentPage = currentPage;
  tableOptions.paginationConfig.pageSize = pageSize;
  getTableList();
};
const tableCheck = ref();
const handleSelectionChange = (val, row) => {
  tableCheck.value = val;
};
const handleSelectionAll = (val) => {
  tableCheck.value = val;
};
const tableSort = ref(2);
const handleSortChange = (column, prop, order) => {
  if (order == 'ascending') {
    tableSort.value = 1;
  } else if (order == 'descending') {
    tableSort.value = 2;
  }
  getTableList();
};

/**
 * 创建刷新工单
 */
const loadingPage = ref(false);
const refreshHref = ref();
const handleAddRefreshOrder = async () => {
  if (!tableCheck.value)
    return ElMessage({
      message: '请先选择数据',
      type: 'warning',
    });
  loadingPage.value = true;
  let res = await axios.getRefreshClick({
    id: tableCheck.value.map((item) => item.id),
  });
  loadingPage.value = false;
  if (res.data.code != 200)
    return ElMessage({
      message: res.data.message,
      type: 'error',
    });
  ElMessage({
    message: '创建成功',
    type: 'success',
  });
  refreshHref.value = res.data.data;
  dialogRefreshOpitons.dialogShow = true;
  getTableList();
};

/**
 查看信息
 */
const handelWatch = (row) => {
  if (!row.rpc_id)
    return ElMessage({
      type: 'warning',
      message: `快捷信息请先在任务管理编辑后查看`,
    });

  let obj = JSON.parse(JSON.stringify(row));
  router.push({
    name: 'messageDetail',
    state: {
      obj,
    },
  });
};

/**
 * 创建刷新工单展示地址
 */
const dialogRefreshOpitons = reactive({
  dialogShow: false,
  title: '查看刷新订单地址',
  width: '40%',
  footButtonList: {
    cancel: {
      type: 'cancel',
      buttonType: 'default',
      btnText: '关 闭',
      btnLoading: false,
      btnLoadingText: '',
    },
  },
});
const handelDialogRefreshButton = () => {
  dialogRefreshOpitons.dialogShow = false;
};

/**
 * 创建删除工单
 */
const dialogDeleteOpitons = reactive({
  dialogShow: false,
  title: '创建删除工单',
  width: '40%',
  footButtonList: {
    cancel: {
      type: 'cancel',
      buttonType: 'default',
      btnText: '取 消',
      btnLoading: false,
      btnLoadingText: '',
    },
    success: {
      type: 'success',
      buttonType: 'primary',
      btnText: '提 交',
      btnLoading: false,
      btnLoadingText: '提交中',
    },
  },
});
const formDeleteOptions = reactive({
  labelWidth: '65px',
  labelPosition: 'left',
});
const formDelete: any = ref({
  key: '', // 姓名
});
const deleteFormRef = ref();
const rulesDelete = reactive({
  key: [
    {
      required: true,
      validator: async (rule: any, value: any, callback: any) => {
        if (!value) return callback(new Error('请填写关键字'));
        if (value.length > 30) return callback(new Error('最多30个字符'));
        callback();
      },
      trigger: ['blur'],
    },
  ],
});
const deleteBackShowInfo = ref();
const handelDelete = (row) => {
  deleteBackShowInfo.value = row;
  dialogDeleteOpitons.dialogShow = true;
};

const handelDialogDeleteButton = (item) => {
  if (item.type == 'cancel') dialogDeleteOpitons.dialogShow = false;
  if (item.type == 'success') handleDeleteSuccess('success');
};
const handleDeleteSuccess = async (type) => {
  deleteFormRef.value.validateForm(async (valid) => {
    if (valid) {
      dialogDeleteOpitons.footButtonList[type].btnLoading = true;
      let res = await axios.messageTaskHandle({
        id: deleteBackShowInfo.value.id,
        style: 3,
        keyword: formDelete.value.key,
      });
      dialogDeleteOpitons.footButtonList[type].btnLoading = false;
      if (res.data.code != 200) return;
      ElMessage({ type: 'success', message: `删除成功` });
      dialogDeleteOpitons.dialogShow = false;
      getTableList();
    }
  });
};

/**
 * init 初始化方法入口
 */
const areaOptions = ref();
const init = async () => {
  // 地区数据
  let cityDate = await axios.getCityChina({
    is_tree: 1,
  });
  areaOptions.value = cityDate.data.data;
  searchItem.value.handelSetOptions(cityDate.data.data, 5);
  getTableList(1);
};
init();
</script>
<template>
  <div class="message" v-loading="loadingPage" element-loading-text="创建中...">
    <!-- 搜索 、表格数据 -->
    <pagesLayout pagesType="alone" class="padding-20">
      <template #center>
        <div class="pageslayout">
          <!-- 搜索 -->
          <div class="pageslayoutHeader">
            <SearchItem :searchOptions="searchOptions" @handelSearch="handelSearch" ref="searchItem"></SearchItem>
          </div>
          <!-- 、表格数据 -->
          <div class="pageslayoutContaint" v-loading="loadingTable" element-loading-text="加载中...">
            <div style="margin-bottom: 15px">
              <el-button type="primary" @click="handleAddRefreshOrder()">
                创建刷新订单
              </el-button>
            </div>
            <Table :columns="columns" :table-data="tableData" :options="tableOptions"
              style="height: calc(100% - 47.39px)" @selection-change="handleSelectionChange"
              @selection-all="handleSelectionAll" @sort-change="handleSortChange"
              @handel-pagination-change="handlePaginationChange"></Table>
          </div>
        </div>
      </template>
    </pagesLayout>
    <!-- 刷新订单地址 -->
    <Dialog :dialog-object="dialogRefreshOpitons" @handelDialogButton="handelDialogRefreshButton">
      <template v-slot:dialogContaint>{{ refreshHref.url_code }}</template>
    </Dialog>
    <!-- 删除订单 弹窗 -->
    <Dialog :dialog-object="dialogDeleteOpitons" @handelDialogButton="handelDialogDeleteButton">
      <template v-slot:dialogContaint>
        <div class="deleteInfo">
          <span>订单编号：{{ deleteBackShowInfo.no }}</span>
          <span>微信昵称：{{ deleteBackShowInfo.nickname }}</span>
          <span>微信ID：{{ deleteBackShowInfo.number }}</span>
        </div>
        <Form :form-object="formDeleteOptions" :form="formDelete" :rules="rulesDelete" ref="deleteFormRef">
          <template v-slot:formContaint>
            <el-form-item label="关键字" prop="key">
              <el-input v-model="formDelete.key" placeholder="限制30个字符" />
            </el-form-item>
          </template>
        </Form>
      </template>
    </Dialog>
  </div>
</template>
<style scoped lang="scss">
.message {
  height: 100%;

  .deleteInfo {
    width: 100%;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;

    span {
      margin-right: 20px;
      line-height: 30px;
    }
  }
}
</style>
